package main

import (
	"encoding/json"
	"fmt"
	"gitallpush/config"
	"gitallpush/git"
	"gitallpush/ui"
	"io"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
	"github.com/lxn/win"
)

// 全局变量声明
var (
	allConfigs                  []config.GitConfig
	progressBar                 *walk.StatusBarItem
	gitNameEntry, gitEmailEntry *walk.LineEdit
	globalConfigCheck           *walk.CheckBox
	repoStatusLabel             *walk.Label
	tempVarManager              *ui.TempVarManager
	tempVarList                 *walk.TableView
	varNameEntry, varValueEntry *walk.LineEdit
	logTextArea                 *walk.TextEdit // 添加日志文本框
)

func main() {
	// 设置日志文件
	logFile := setupLogging()
	defer logFile.Close()

	// 初始化临时变量管理器
	tempVarManager = ui.NewTempVarManager()

	var mainWindow *walk.MainWindow
	var configList *walk.TableView
	var platformEntry, urlEntry, branchEntry, workDirEntry *walk.LineEdit
	var commitMsgEntry *walk.TextEdit
	var statusBar *walk.StatusBarItem
	var searchEntry *walk.LineEdit
	var groupCombo *walk.ComboBox
	var remoteNameEntry, remoteURLEntry *walk.LineEdit

	configs, _ := config.LoadConfig()
	allConfigs = configs // 保存一份完整配置
	model := ui.NewConfigModel(configs)

	mw := MainWindow{
		AssignTo: &mainWindow,
		Title:    "Git多端推送工具",
		MinSize:  Size{1000, 700},
		Layout:   VBox{MarginsZero: true},
		Font: Font{
			Family:    "Microsoft YaHei",
			PointSize: 9,
		},
		MenuItems: []MenuItem{
			Menu{
				Text: "文件",
				Items: []MenuItem{
					Action{
						Text:     "新建配置 (Ctrl+N)",
						Shortcut: Shortcut{Modifiers: walk.ModControl, Key: walk.KeyN},
						OnTriggered: func() {
							clearForm(platformEntry, urlEntry, branchEntry)
						},
					},
					Action{
						Text:     "保存配置 (Ctrl+S)",
						Shortcut: Shortcut{Modifiers: walk.ModControl, Key: walk.KeyS},
						OnTriggered: func() {
							config.SaveConfig(model.Configs())
							statusBar.SetText("配置已保存")
						},
					},
					Action{
						Text:     "推送 (Ctrl+P)",
						Shortcut: Shortcut{Modifiers: walk.ModControl, Key: walk.KeyP},
						OnTriggered: func() {
							var wg sync.WaitGroup
							total := 0
							for _, cfg := range model.Configs() {
								if cfg.Enabled {
									total++
								}
							}
							current := 0

							for _, cfg := range model.Configs() {
								if cfg.Enabled {
									wg.Add(1)
									go func(c config.GitConfig) {
										defer wg.Done()
										statusBar.SetText(fmt.Sprintf("正在推送到 %s...", c.Platform))
										if err := git.Push(tempVarManager.ReplaceVars(c.RepoURL), c.Branch); err != nil {
											walk.MsgBox(mainWindow, "错误",
												fmt.Sprintf("推送到 %s 失败: %v", c.Platform, err),
												walk.MsgBoxIconError)
										} else {
											walk.MsgBox(mainWindow, "成功",
												fmt.Sprintf("成功推送到 %s", c.Platform),
												walk.MsgBoxIconInformation)
										}
										current++
										progressBar.SetText(fmt.Sprintf("%d/%d", current, total))
									}(cfg)
								}
							}
							go func() {
								wg.Wait()
								progressBar.SetText("")
								statusBar.SetText("所有推送任务完成")
							}()
						},
					},
					Action{
						Text: "导入配置",
						OnTriggered: func() {
							dlg := new(walk.FileDialog)
							dlg.Title = "导入配置文件"
							dlg.Filter = "JSON文件 (*.json)|*.json"

							if ok, _ := dlg.ShowOpen(mainWindow); !ok {
								return
							}

							file, err := os.ReadFile(dlg.FilePath)
							if err != nil {
								walk.MsgBox(mainWindow, "错误", "读取文件失败: "+err.Error(), walk.MsgBoxIconError)
								return
							}

							var newConfigs []config.GitConfig
							if err := json.Unmarshal(file, &newConfigs); err != nil {
								walk.MsgBox(mainWindow, "错误", "解析配置失败: "+err.Error(), walk.MsgBoxIconError)
								return
							}

							configs := append(model.Configs(), newConfigs...)
							model.SetConfigs(configs)
							config.SaveConfig(model.Configs())
							configList.SetModel(model)
							log.Printf("导入了 %d 个配置", len(newConfigs))
						},
					},
					Action{
						Text: "导出配置",
						OnTriggered: func() {
							dlg := new(walk.FileDialog)
							dlg.Title = "导出配置文件"
							dlg.Filter = "JSON文件 (*.json)|*.json"

							if ok, _ := dlg.ShowSave(mainWindow); !ok {
								return
							}

							data, err := json.MarshalIndent(model.Configs(), "", "    ")
							if err != nil {
								walk.MsgBox(mainWindow, "错误", "序列化配置失败: "+err.Error(), walk.MsgBoxIconError)
								return
							}

							if err := os.WriteFile(dlg.FilePath, data, 0644); err != nil {
								walk.MsgBox(mainWindow, "错误", "保存文件失败: "+err.Error(), walk.MsgBoxIconError)
								return
							}

							log.Printf("导出了 %d 个配置到 %s", len(model.Configs()), dlg.FilePath)
						},
					},
					Separator{},
					Action{
						Text:        "退出",
						OnTriggered: func() { mainWindow.Close() },
					},
				},
			},
			Menu{
				Text: "帮助",
				Items: []MenuItem{
					Action{
						Text: "查看日志",
						OnTriggered: func() {
							logDir := filepath.Join(os.Getenv("APPDATA"), "git-push-tool", "logs")
							exec.Command("explorer", logDir).Start()
						},
					},
					Action{
						Text: "关于",
						OnTriggered: func() {
							walk.MsgBox(mainWindow, "关于",
								"Git多端推送工具 v1.0\n\n"+
									"用于同时推送Git仓库到多个远程平台\n"+
									"支持配置管理和批量操作",
								walk.MsgBoxIconInformation)
						},
					},
				},
			},
		},
		ToolBar: ToolBar{
			ButtonStyle: ToolBarButtonTextOnly,
			Items: []MenuItem{
				Action{
					Text:        "新建",
					OnTriggered: func() { clearForm(platformEntry, urlEntry, branchEntry) },
				},
				Action{
					Text: "保存",
					OnTriggered: func() {
						config.SaveConfig(model.Configs())
						statusBar.SetText("配置已保存")
					},
				},
				Separator{},
				Action{
					Text: "提交",
					OnTriggered: func() {
						if commitMsgEntry.Text() == "" {
							walk.MsgBox(mainWindow, "提示", "请输入提交信息", walk.MsgBoxIconInformation)
							return
						}
						if err := git.Commit(commitMsgEntry.Text()); err != nil {
							walk.MsgBox(mainWindow, "错误", "提交失败: "+err.Error(), walk.MsgBoxIconError)
							return
						}
						commitMsgEntry.SetText("")
						statusBar.SetText("提交成功")
					},
				},
				Action{
					Text: "推送",
					OnTriggered: func() {
						hasChanges, _ := git.HasUncommittedChanges()
						if hasChanges {
							if res := walk.MsgBox(mainWindow, "警告",
								"当前有未提交的更改，是否继续推送？",
								walk.MsgBoxYesNo|walk.MsgBoxIconWarning); res != walk.DlgCmdYes {
								return
							}
						}

						var wg sync.WaitGroup
						total := 0
						for _, cfg := range model.Configs() {
							if cfg.Enabled {
								total++
							}
						}
						current := 0

						for _, cfg := range model.Configs() {
							if cfg.Enabled {
								wg.Add(1)
								go func(c config.GitConfig) {
									defer wg.Done()
									statusBar.SetText(fmt.Sprintf("正在推送到 %s...", c.Platform))
									if err := git.Push(tempVarManager.ReplaceVars(c.RepoURL), c.Branch); err != nil {
										walk.MsgBox(mainWindow, "错误",
											fmt.Sprintf("推送到 %s 失败: %v", c.Platform, err),
											walk.MsgBoxIconError)
									} else {
										walk.MsgBox(mainWindow, "成功",
											fmt.Sprintf("成功推送到 %s", c.Platform),
											walk.MsgBoxIconInformation)
									}
									current++
									progressBar.SetText(fmt.Sprintf("%d/%d", current, total))
								}(cfg)
							}
						}
						go func() {
							wg.Wait()
							progressBar.SetText("")
							statusBar.SetText("所有推送任务完成")
						}()
					},
				},
			},
		},
		Children: []Widget{
			HSplitter{
				Children: []Widget{
					// 左侧面板
					Composite{
						Layout:        VBox{Margins: Margins{Right: 5}}, // 添加右边距
						StretchFactor: 2,                                // 占据更多空间
						Children: []Widget{
							// 搜索框部分
							Composite{
								Layout: HBox{Margins: Margins{Top: 5, Bottom: 5}},
								Children: []Widget{
									Label{
										Text:    "搜索:",
										MinSize: Size{Width: 40},
									},
									LineEdit{
										AssignTo: &searchEntry,
										MinSize:  Size{Width: 200},
										OnTextChanged: func() {
											text := strings.ToLower(searchEntry.Text())
											filtered := make([]config.GitConfig, 0)
											for _, cfg := range model.Configs() {
												if strings.Contains(strings.ToLower(cfg.Platform), text) ||
													strings.Contains(strings.ToLower(cfg.RepoURL), text) ||
													strings.Contains(strings.ToLower(cfg.Branch), text) {
													filtered = append(filtered, cfg)
												}
											}
											model.SetConfigs(filtered)
											configList.SetModel(model)
										},
									},
								},
							},
							// 配置列表
							Composite{
								Layout: VBox{},
								Children: []Widget{
									Label{
										Text:      "配置列表",
										Font:      Font{PointSize: 12, Bold: true},
										TextColor: walk.RGB(220, 220, 220),
									},
									TableView{
										AssignTo:         &configList,
										Model:            model,
										AlternatingRowBG: true,
										StyleCell: func(style *walk.CellStyle) {
											style.BackgroundColor = walk.Color(win.GetSysColor(win.COLOR_WINDOW))
											if style.Row()%2 == 0 {
												style.BackgroundColor = walk.Color(win.GetSysColor(win.COLOR_BTNFACE))
											}
										},
										Columns: []TableViewColumn{
											{Title: "启用", Width: 50},
											{Title: "分组", Width: 100},
											{Title: "平台", Width: 150},
											{Title: "仓库URL", Width: 300},
											{Title: "分支", Width: 100},
										},
										CheckBoxes:     true,
										MultiSelection: true,
										OnItemActivated: func() {
											// 双击编辑
											if index := configList.CurrentIndex(); index != -1 {
												configs := model.Configs()
												cfg := configs[index]
												platformEntry.SetText(cfg.Platform)
												urlEntry.SetText(cfg.RepoURL)
												branchEntry.SetText(cfg.Branch)
											}
										},
									},
								},
							},
						},
					},

					// 右侧面板
					Composite{
						Layout:        VBox{Margins: Margins{Left: 5}}, // 添加左边距
						StretchFactor: 1,                               // 占据较少空间
						Children: []Widget{
							// Git仓库部分
							GroupBox{
								Title:  "Git仓库",
								Layout: VBox{Margins: Margins{10, 10, 10, 10}},
								Children: []Widget{
									// 工作目录选择
									Composite{
										Layout: HBox{Spacing: 5},
										Children: []Widget{
											Label{
												Text:    "工作目录:",
												MinSize: Size{Width: 60},
											},
											LineEdit{
												AssignTo: &workDirEntry,
												ReadOnly: true,
												MinSize:  Size{Width: 200},
											},
											PushButton{
												Text:    "选择",
												MinSize: Size{Width: 60},
												OnClicked: func() {
													dlg := new(walk.FileDialog)
													dlg.Title = "选择Git仓库目录"

													if ok, _ := dlg.ShowBrowseFolder(mainWindow); !ok {
														return
													}

													if err := git.SetWorkingDir(dlg.FilePath); err != nil {
														walk.MsgBox(mainWindow, "错误",
															"设置工作目录失败: "+err.Error(),
															walk.MsgBoxIconError)
														return
													}

													workDirEntry.SetText(dlg.FilePath)
													updateRepoStatus() // 更新仓库状态
												},
											},
										},
									},
									// Git账号配置
									GroupBox{
										Title:  "Git账号配置",
										Layout: Grid{Columns: 3, Spacing: 5},
										Children: []Widget{
											Label{Text: "用户名:"},
											LineEdit{AssignTo: &gitNameEntry},
											PushButton{
												Text:    "获取",
												MinSize: Size{Width: 60},
												OnClicked: func() {
													name, email, _ := git.GetGitConfig(false) // 获取局部配置
													gitNameEntry.SetText(name)
													gitEmailEntry.SetText(email)
												},
											},
											Label{Text: "邮箱:"},
											LineEdit{AssignTo: &gitEmailEntry},
											PushButton{
												Text:    "设置",
												MinSize: Size{Width: 60},
												OnClicked: func() {
													if err := git.SetGitConfig(
														gitNameEntry.Text(),
														gitEmailEntry.Text(),
														false, // 设置为局部配置
													); err != nil {
														walk.MsgBox(mainWindow, "错误",
															"设置Git账号失败: "+err.Error(),
															walk.MsgBoxIconError)
														return
													}
													statusBar.SetText("Git账号设置成功")
												},
											},
											CheckBox{
												Text:     "全局设置",
												AssignTo: &globalConfigCheck,
												OnCheckedChanged: func() {
													name, email, _ := git.GetGitConfig(globalConfigCheck.Checked())
													gitNameEntry.SetText(name)
													gitEmailEntry.SetText(email)
												},
											},
										},
									},
									// 提交信息
									Composite{
										Layout: VBox{Spacing: 5},
										Children: []Widget{
											Label{Text: "提交信息:"},
											TextEdit{
												AssignTo: &commitMsgEntry,
												MinSize:  Size{Height: 60},
											},
										},
									},
								},
							},

							// 分组管理
							GroupBox{
								Title:  "分组管理",
								Layout: HBox{Margins: Margins{5, 5, 5, 5}, Spacing: 5},
								Children: []Widget{
									ComboBox{
										AssignTo: &groupCombo,
										Model:    append([]string{"全部"}, getGroups(model.Configs())...),
										MinSize:  Size{Width: 150},
										OnCurrentIndexChanged: func() {
											if idx := groupCombo.CurrentIndex(); idx != -1 {
												group := groupCombo.Model().([]string)[idx]
												model.SetConfigs(allConfigs)
												if group != "全部" {
													filtered := make([]config.GitConfig, 0)
													for _, cfg := range model.Configs() {
														if cfg.Group == group {
															filtered = append(filtered, cfg)
														}
													}
													model.SetConfigs(filtered)
												}
												configList.SetModel(model)
											}
										},
									},
									PushButton{
										Text:    "新建分组",
										MinSize: Size{Width: 80},
										OnClicked: func() {
											var dlg *walk.Dialog
											var input *walk.LineEdit
											var result string

											dialogConfig := Dialog{
												AssignTo: &dlg,
												Title:    "新建分组",
												MinSize:  Size{Width: 300, Height: 100},
												Layout:   VBox{},
												Children: []Widget{
													Composite{
														Layout: HBox{},
														Children: []Widget{
															Label{Text: "分组名称:"},
															LineEdit{AssignTo: &input},
														},
													},
													Composite{
														Layout: HBox{},
														Children: []Widget{
															HSpacer{},
															PushButton{
																Text: "确定",
																OnClicked: func() {
																	if text := input.Text(); text != "" {
																		result = text
																		dlg.Accept()
																	}
																},
															},
															PushButton{
																Text: "取消",
																OnClicked: func() {
																	dlg.Cancel()
																},
															},
														},
													},
												},
											}

											if err := dialogConfig.Create(mainWindow); err != nil {
												walk.MsgBox(mainWindow, "错误", "创建对话框失败: "+err.Error(), walk.MsgBoxIconError)
												return
											}

											if dlg.Run() == walk.DlgCmdOK && result != "" {
												// 添加新分组
												groups := getGroups(model.Configs())
												for _, g := range groups {
													if g == result {
														walk.MsgBox(mainWindow, "错误", "分组已存在", walk.MsgBoxIconError)
														return
													}
												}
												// 更新当前选中的配置的分组
												if indices := configList.SelectedIndexes(); len(indices) > 0 {
													configs := model.Configs()
													for _, idx := range indices {
														configs[idx].Group = result
													}
													model.SetConfigs(configs)
													config.SaveConfig(model.Configs())
													configList.SetModel(model)
												}
											}
										},
									},
								},
							},

							// 批量操作
							GroupBox{
								Title:  "批量操作",
								Layout: HBox{Margins: Margins{5, 5, 5, 5}, Spacing: 5},
								Children: []Widget{
									PushButton{
										Text:    "全部启用",
										MinSize: Size{Width: 80},
										OnClicked: func() {
											configs := model.Configs()
											for i := range configs {
												configs[i].Enabled = true
											}
											model.SetConfigs(configs)
											config.SaveConfig(model.Configs())
											configList.SetModel(model)
										},
									},
									PushButton{
										Text:    "全部禁用",
										MinSize: Size{Width: 80},
										OnClicked: func() {
											configs := model.Configs()
											for i := range configs {
												configs[i].Enabled = false
											}
											model.SetConfigs(configs)
											config.SaveConfig(model.Configs())
											configList.SetModel(model)
										},
									},
									PushButton{
										Text:    "推送到所有启用平台",
										MinSize: Size{Width: 150},
										OnClicked: func() {
											var wg sync.WaitGroup
											total := 0
											for _, cfg := range model.Configs() {
												if cfg.Enabled {
													total++
												}
											}
											current := 0

											for _, cfg := range model.Configs() {
												if cfg.Enabled {
													wg.Add(1)
													go func(c config.GitConfig) {
														defer wg.Done()
														statusBar.SetText(fmt.Sprintf("正在推送到 %s...", c.Platform))
														if err := git.Push(tempVarManager.ReplaceVars(c.RepoURL), c.Branch); err != nil {
															walk.MsgBox(mainWindow, "错误",
																fmt.Sprintf("推送到 %s 失败: %v", c.Platform, err),
																walk.MsgBoxIconError)
														} else {
															walk.MsgBox(mainWindow, "成功",
																fmt.Sprintf("成功推送到 %s", c.Platform),
																walk.MsgBoxIconInformation)
														}
														current++
														progressBar.SetText(fmt.Sprintf("%d/%d", current, total))
													}(cfg)
												}
											}
											go func() {
												wg.Wait()
												progressBar.SetText("")
												statusBar.SetText("所有推送任务完成")
											}()
										},
									},
								},
							},

							// 远程仓库管理
							GroupBox{
								Title:  "远程仓库管理",
								Layout: Grid{Columns: 3},
								Children: []Widget{
									Label{Text: "名称:"},
									LineEdit{AssignTo: &remoteNameEntry},
									PushButton{
										Text:    "获取",
										MinSize: Size{Width: 60},
										OnClicked: func() {
											remotes, err := git.ListRemotes()
											if err != nil {
												walk.MsgBox(mainWindow, "错误", "获取远程仓库列表失败: "+err.Error(), walk.MsgBoxIconError)
												return
											}

											// 如果输入框有值，直接获取对应的远程仓库
											if name := remoteNameEntry.Text(); name != "" {
												if url, ok := remotes[name]; ok {
													remoteURLEntry.SetText(url)
													statusBar.SetText("已获取远程仓库 " + name + " 的地址")
													return
												}
											}

											// 显示选择对话框
											if name, url, ok := ui.ShowRemoteDialog(mainWindow, remotes); ok {
												remoteNameEntry.SetText(name)
												remoteURLEntry.SetText(url)
												statusBar.SetText("已获取远程仓库 " + name + " 的地址")
											}
										},
									},
									Label{Text: "地址:"},
									LineEdit{AssignTo: &remoteURLEntry},
									PushButton{
										Text:    "设置",
										MinSize: Size{Width: 60},
										OnClicked: func() {
											name := remoteNameEntry.Text()
											url := remoteURLEntry.Text()
											if name == "" || url == "" {
												walk.MsgBox(mainWindow, "提示", "请输入远程仓库名称和地址", walk.MsgBoxIconInformation)
												return
											}

											if err := git.SetRemoteURL(name, url); err != nil {
												walk.MsgBox(mainWindow, "错误", "设置远程仓库失败: "+err.Error(), walk.MsgBoxIconError)
												return
											}

											// 添加到配置列表
											newConfig := config.GitConfig{
												Enabled:  true,
												Group:    "默认",
												Platform: name,
												RepoURL:  url,
												Branch:   "master", // 默认使用 master 分支
											}

											// 检查是否已存在相同的配置
											exists := false
											configs := model.Configs()
											for i, cfg := range configs {
												if cfg.Platform == name {
													configs[i] = newConfig
													exists = true
													break
												}
											}

											if !exists {
												configs = append(configs, newConfig)
											}

											model.SetConfigs(configs)
											config.SaveConfig(model.Configs())
											configList.SetModel(model)

											statusBar.SetText("远程仓库设置成功并已添加到配置列表")

											// 清空输入框
											remoteNameEntry.SetText("")
											remoteURLEntry.SetText("")
										},
									},
								},
							},

							// 临时变量管理
							GroupBox{
								Title:  "临时变量管理",
								Layout: VBox{},
								Children: []Widget{
									TableView{
										AssignTo:         &tempVarList,
										AlternatingRowBG: true,
										Columns: []TableViewColumn{
											{Title: "变量名", Width: 150},
											{Title: "变量值", Width: 300},
										},
										Model: ui.NewTempVarModel(tempVarManager.GetVars()),
									},
									Composite{
										Layout: HBox{},
										Children: []Widget{
											Label{Text: "变量名:"},
											LineEdit{AssignTo: &varNameEntry},
											Label{Text: "变量值:"},
											LineEdit{AssignTo: &varValueEntry},
											PushButton{
												Text: "添加",
												OnClicked: func() {
													name := varNameEntry.Text()
													value := varValueEntry.Text()
													if name == "" || value == "" {
														return
													}

													tempVarManager.AddOrUpdateVar(name, value)
													tempVarList.SetModel(ui.NewTempVarModel(tempVarManager.GetVars()))

													varNameEntry.SetText("")
													varValueEntry.SetText("")
												},
											},
										},
									},
								},
							},

							// 添加日志显示区域
							GroupBox{
								Title:  "日志",
								Layout: VBox{},
								Children: []Widget{
									TextEdit{
										AssignTo:  &logTextArea,
										ReadOnly:  true,
										VScroll:   true,
										MaxLength: 1000000,
									},
								},
							},
						},
					},
				},
			},
		},
		StatusBarItems: []StatusBarItem{
			{
				AssignTo: &statusBar,
				Text:     "就绪",
				Width:    300,
			},
			{
				AssignTo: &progressBar,
				Width:    200,
			},
		},
	}

	if err := mw.Create(); err != nil {
		log.Fatal(err)
	}

	// 设置状态栏文本
	if statusBar != nil {
		statusBar.SetText("就绪")
	}
	if progressBar != nil {
		progressBar.SetText("")
	}

	// 更新仓库状态
	updateRepoStatus()

	model.SetView(configList)

	// 在 mw.Create() 之后，mainWindow.Run() 之前添加右键菜单设置
	contextMenu, _ := walk.NewMenu()
	enableAction := walk.NewAction()
	enableAction.SetText("启用选中")
	enableAction.Triggered().Attach(func() {
		for _, index := range configList.SelectedIndexes() {
			configs := model.Configs()
			configs[index].Enabled = true
			model.SetConfigs(configs)
		}
		config.SaveConfig(model.Configs())
		configList.SetModel(model)
	})
	contextMenu.Actions().Add(enableAction)

	disableAction := walk.NewAction()
	disableAction.SetText("禁用选中")
	disableAction.Triggered().Attach(func() {
		for _, index := range configList.SelectedIndexes() {
			configs := model.Configs()
			configs[index].Enabled = false
			model.SetConfigs(configs)
		}
		config.SaveConfig(model.Configs())
		configList.SetModel(model)
	})
	contextMenu.Actions().Add(disableAction)

	contextMenu.Actions().Add(walk.NewSeparatorAction())

	deleteAction := walk.NewAction()
	deleteAction.SetText("删除选中")
	deleteAction.Triggered().Attach(func() {
		if indices := configList.SelectedIndexes(); len(indices) > 0 {
			configs := model.Configs()
			for i := len(indices) - 1; i >= 0; i-- {
				configs = append(configs[:indices[i]], configs[indices[i]+1:]...)
			}
			model.SetConfigs(configs)
			config.SaveConfig(model.Configs())
			configList.SetModel(model)
		}
	})
	contextMenu.Actions().Add(deleteAction)

	configList.SetContextMenu(contextMenu)

	// 创建自定义日志写入器
	logWriter := ui.NewLogWriter(logTextArea)
	log.SetOutput(io.MultiWriter(logWriter, os.Stdout))

	mainWindow.Run()
}

func clearForm(entries ...*walk.LineEdit) {
	for _, entry := range entries {
		if entry != nil {
			entry.SetText("")
		}
	}
}

func setupLogging() *os.File {
	logDir := filepath.Join(os.Getenv("APPDATA"), "git-push-tool", "logs")
	os.MkdirAll(logDir, 0755)

	logPath := filepath.Join(logDir, time.Now().Format("2006-01-02")+".log")
	f, err := os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalf("error opening log file: %v", err)
	}

	// 日志输出到文件和标准输出，UI的日志输出在主窗口创建后设置
	log.SetOutput(io.MultiWriter(f))
	return f
}

func getGroups(configs []config.GitConfig) []string {
	groups := make(map[string]bool)
	for _, cfg := range configs {
		groups[cfg.Group] = true
	}
	groupList := make([]string, 0, len(groups))
	for group := range groups {
		groupList = append(groupList, group)
	}
	return groupList
}

func updateRepoStatus() {
	if repoStatusLabel == nil {
		return
	}

	hasChanges, err := git.HasUncommittedChanges()
	if err != nil {
		repoStatusLabel.SetText("无法获取状态: " + err.Error())
		return
	}

	if hasChanges {
		repoStatusLabel.SetText("有未提交的更改")
	} else {
		repoStatusLabel.SetText("无未提交更改")
	}
}
